package com.ylx;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {

    /**
     * 驼峰/下划线互转
     * @param str
     * @return
     */
    public static String toCamelCase(String str){
        Matcher matcher = Pattern.compile("[a-zA-z]*_[a-zA-z]*").matcher(str);
        if (matcher.find()) {
            return upperCamelCase2LineSeparation(str);
        }else {
            return camelCase2LineSeparation(str);
        }
    }

    /**
     * 转驼峰
     * @param str
     * @return
     */
    public static String upperCamelCase2LineSeparation(String str){
        Matcher matcher = Pattern.compile("[a-zA-z]*_[a-zA-z]*").matcher(str);
        while (matcher.find()) {
            String group = matcher.group();
            String toLowerCase = group.toLowerCase();
            StringBuffer sb = new StringBuffer();
            Matcher matcher1 = Pattern.compile("_(\\w)").matcher(toLowerCase);
            while (matcher1.find()) {
                matcher1.appendReplacement(sb, matcher1.group(1).toUpperCase());
            }
            matcher1.appendTail(sb);

            str = str.replace(group,sb.toString());
        }
        return str;
    }

    /**
     * 转下划线
     * @param camelWord
     * @return
     */
    public static String camelCase2LineSeparation(String camelWord) {
        Matcher matcher = Pattern.compile("[a-zA-z\\d]+").matcher(camelWord);
        while (matcher.find()){
            String group = matcher.group();
            Matcher matcher1 = Pattern.compile("([A-Z][a-z])|([a-z][A-Z])").matcher(group);

            StringBuffer word = new StringBuffer();
            while (matcher1.find()){
                matcher1.appendReplacement(word, matcher1.group(0).replaceAll("(.$)", "_$1"));
            }
            matcher1.appendTail(word);
            String toLowerCase = word.toString().toLowerCase();
            camelWord = camelWord.replace(group,toLowerCase);
        }
        return  camelWord;
    }

}
